﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Collections.ObjectModel;

namespace SignalLab
{
  public static class SettingsManager
  {
    public const string ACCOUNT_KEY = "Account";
    public static SettingItemViewModel Account
    {
      get
      {
        if (_Account == null)
        {
          _Account = getDefaultAccount();
          if (IsolatedStorageSettings.ApplicationSettings.Contains(ACCOUNT_KEY))
          {
            _Account.Items = (ObservableCollection<StringNameValue>)IsolatedStorageSettings.ApplicationSettings[ACCOUNT_KEY];
          }
        }
        return _Account;
      }
    }
    private static SettingItemViewModel _Account;

    public const string CATEGORIES_KEY = "Categories";
    public static SettingItemViewModel Categories
    {
      get
      {
        if (_Categories == null)
        {
          _Categories = new SettingItemViewModel()
          {
            Key = CATEGORIES_KEY,
            SettingName = "Categories",
            Description = "Organize your signal records to categories",

          };
          if (IsolatedStorageSettings.ApplicationSettings.Contains(CATEGORIES_KEY))
          {
            _Categories.Items = (ObservableCollection<StringNameValue>)IsolatedStorageSettings.ApplicationSettings[CATEGORIES_KEY];
          }
          else
          {
            _Categories.Items = new ObservableCollection<StringNameValue>()
            {
              new StringNameValue() { Name= "Category", Value="Default" }
            };
          }
        }
        return _Categories;
      }
    }
    private static SettingItemViewModel _Categories;

    public static void SaveSetting(SettingItemViewModel setting)
    {
      var appSettings = IsolatedStorageSettings.ApplicationSettings;
      if (appSettings.Contains(setting.Key))
      {
        appSettings[setting.Key] = setting.Items;
      }
      else
      {
        appSettings.Add(setting.Key, setting.Items);
      }

      if (setting.Key == CATEGORIES_KEY)
      {
        AppManager.Instance.GetCategories();
      }
    }

    private static SettingItemViewModel getDefaultAccount()
    {
      return new SettingItemViewModel()
      {
        SettingName = "Account",
        Description = "You currenty have no server account",
        Key = ACCOUNT_KEY,
        Items = new ObservableCollection<StringNameValue>()
        {
          new StringNameValue() { Name="server" },
          new StringNameValue() { Name="username" },
          new StringNameValue() { Name="password" }
        }
      };

    }

  }
}
